using System;
using System.Collections.Generic;
using System.Text;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine.Networking;

namespace Client.Hotfix
{
    [UGFM(UGFMWeight.HttpService)]
    public class HttpService : IAwake
    {
        private string defaultUrl = "http://192.168.6.233:5233";
        private readonly Dictionary<string, string> defaultHeaders = new();
        public void Awake()
        {
            this.Log("HttpService is running");
        }

        public void Post(HttpRequest request, Action<HttpResponse> callBack)
        {
            if (string.IsNullOrEmpty(request.Url))
            {
                request.Url = defaultUrl;
            }

            if (request.Headers == null)
            {
                request.Headers = defaultHeaders;
            }

            request.SetMethod("POST");

            SendWebReques(request, callBack);
        }

        public void Get(HttpRequest request, Action<HttpResponse> callBack)
        {
            if (string.IsNullOrEmpty(request.Url))
            {
                request.Url = defaultUrl;
            }

            if (request.Headers == null)
            {
                request.Headers = defaultHeaders;
            }

            request.SetMethod("GET");

            SendWebReques(request, callBack);
        }

        public void Put(HttpRequest request, Action<HttpResponse> callBack)
        {
            if (string.IsNullOrEmpty(request.Url))
            {
                request.Url = defaultUrl;
            }

            if (request.Headers == null)
            {
                request.Headers = defaultHeaders;
            }
            request.SetMethod("PUT");
            SendWebReques(request, callBack);
        }


        public async void SendWebReques(HttpRequest request, Action<HttpResponse> callBack)
        {
            using (UnityWebRequest webRequest = CreateWebRequest(request))
            {
                webRequest.timeout = request.Timeout;
                await webRequest.SendWebRequest().ToUniTask();

                HttpResponse response = new HttpResponse();
                response.IsSuccess = webRequest.result == UnityWebRequest.Result.Success;
                if (webRequest.result == UnityWebRequest.Result.Success)
                {
                    response.Text = webRequest.downloadHandler.text;
                    response.Data = webRequest.downloadHandler.data;
                }
                else
                {
                    response.Error = webRequest.error;
                    response.Text = webRequest.downloadHandler.text;
                }
                callBack?.Invoke(response);
            }
        }


        private UnityWebRequest CreateWebRequest(HttpRequest request)
        {
            UnityWebRequest webRequest;

            switch (request.Method.ToUpper())
            {
                case "GET":
                    webRequest = UnityWebRequest.Get(request.Url);
                    break;
                case "POST":
                    webRequest = CreatePostRequest(request);
                    break;
                case "PUT":
                    webRequest = CreatePutRequest(request);
                    break;
                case "DELETE":
                    webRequest = UnityWebRequest.Delete(request.Url);
                    break;
                default:
                    throw new ArgumentException($"不支持的HTTP方法: {request.Method}");
            }

            // 添加默认headers
            foreach (var header in request.Headers)
            {
                webRequest.SetRequestHeader(header.Key, header.Value);
            }

            return webRequest;
        }

        private UnityWebRequest CreatePostRequest(HttpRequest request)
        {
            if (request.Body == null)
                return new UnityWebRequest(request.Url, "POST");
            string jsonBody = JsonConvert.SerializeObject(request.Body);
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
            string url = $"{request.Url}/{request.Api}";
            var webRequest = new UnityWebRequest(url, "POST");
            webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = new DownloadHandlerBuffer();
            webRequest.SetRequestHeader("Content-Type", request.ContentType);
            return webRequest;
        }

        private UnityWebRequest CreatePutRequest(HttpRequest request)
        {
            if (request.Body == null)
                return UnityWebRequest.Put(request.Url, "");

            string jsonBody = JsonConvert.SerializeObject(request.Body);
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
            string url = $"{request.Url}/{request.Api}";
            var webRequest = new UnityWebRequest(url, "PUT");
            webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = new DownloadHandlerBuffer();
            webRequest.SetRequestHeader("Content-Type", request.ContentType);

            return webRequest;
        }
    }

}
